import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class UVCounter {
    public static void main(String args[]) throws Exception, IOException, ClassNotFoundException, InterruptedException {
        String inputPath = null;
        String outputPath = null;
        for (int i = 0; i < args.length; i++) {
            if (args[i].toLowerCase().equals("--input") || args[i].toLowerCase().equals("-i")) {
                if (i + 1 < args.length) {
                    inputPath = args[i + 1];
                    i++;
                }
            } else if (args[i].toLowerCase().equals("-output") || args[i].toLowerCase().equals("-o")) {
                if (i + 1 < args.length) {
                    outputPath = args[i + 1];
                    i++;
                }
            }
        }
        if (inputPath == null) throw new Exception("No input path set!");
        if (outputPath == null) throw new Exception("No output path set!");

        Job job = Job.getInstance(new Configuration());
        job.setJarByClass(UVCounter.class);

        job.setMapperClass(UVMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        FileInputFormat.setInputPaths(job, new Path(inputPath));

        job.setReducerClass(UVReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        FileOutputFormat.setOutputPath(job, new Path(outputPath));

        job.waitForCompletion(true);
        System.out.println("Finished UV count task.");
    }
}
